package com.bookbuf.social.share.content.media.image.converter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

import com.bookbuf.social.secure.AesHelper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created by robert on 16/7/4.
 */
public class UrlConverter extends ConfiguredConverter {
	private String url = null;

	public UrlConverter (String url) {
		this.url = url;
	}

	public File asFile () {
		File file = null;

		try {
			file = this.getConfig ().generateCacheFile (AesHelper.md5 (this.url));
			FileOutputStream outputStream = new FileOutputStream (file);
			byte[] asBinary = this.asBinary ();
			outputStream.write (asBinary);
			outputStream.flush ();
			outputStream.close ();
		} catch (Exception e) {
			e.printStackTrace ();
		}

		return file;
	}

	public String asUrl () {
		return this.url;
	}

	public byte[] asBinary () {
		return getNetData (this.url);
	}

	public Bitmap asBitmap () {
		byte[] bytes = this.asBinary ();
		return bytes != null ? BitmapFactory.decodeByteArray (bytes, 0, bytes.length) : null;
	}

	public byte[] getNetData (String url) {
		if (TextUtils.isEmpty (url)) {
			return null;
		} else {
			ByteArrayOutputStream outputStream = null;
			InputStream inputStream = null;

			try {
				outputStream = new ByteArrayOutputStream ();
				inputStream = (InputStream) (new URL (url)).openConnection ().getContent ();
				Log.d ("image", "getting image from url" + url);
				byte[] buffer = new byte[4096];

				int byteCount;
				while ((byteCount = inputStream.read (buffer)) != -1) {
					outputStream.write (buffer, 0, byteCount);
				}
				return outputStream.toByteArray ();
			} catch (Exception e) {
				e.printStackTrace ();
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close ();
					} catch (IOException e) {
						e.printStackTrace ();
					} finally {
						if (outputStream != null) {
							try {
								outputStream.close ();
							} catch (IOException e) {
								e.printStackTrace ();
							}
						}

					}
				}

			}

			return null;
		}
	}
}